package com.xgk.boot.module.core.framework.interceptor;


import cn.hutool.extra.spring.SpringUtil;
import com.xgk.boot.framework.security.core.util.SecurityFrameworkUtils;
import com.xgk.boot.module.core.mq.message.log.OrderApiLogMessage;
import com.xgk.boot.module.core.mq.producer.log.OrderApiLogProducer;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import okio.Buffer;

import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpLogInterceptor implements Interceptor {

    private OrderApiLogProducer apiLogProducer;

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.nanoTime();
        OrderApiLogMessage orderApiLogMessage = new OrderApiLogMessage();
        log.info("request: [{}] {}", request.method(), request.url());
        if (request.body() != null) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            log.info("Request Body: {}", buffer.readUtf8());
        }
//        SecurityFrameworkUtils
        try {
            Response response = chain.proceed(request);
            long durationMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
            log.info("response: [{}] {} ({}ms)", response.code(), request.url(), durationMs);

            if (response.body() != null && response.body().contentLength() > 0) {
                MediaType contentType = response.body().contentType();
                String bodyString = response.peekBody(Long.MAX_VALUE).string();
                log.info("Response Body: {}", bodyString);
            }
            return response;
        } catch (IOException e) {
            log.error("HTTP 调用失败 [{} {}]: {}", request.method(), request.url(), e.getMessage(), e);
            throw e;
        }finally {

//            getApiLogProducer().sendOrderApiLog();
        }
    }

    private OrderApiLogProducer getApiLogProducer() {
        if (apiLogProducer == null) {
            synchronized (this) {
                if (apiLogProducer == null) {
                    apiLogProducer = SpringUtil.getBean(OrderApiLogProducer.class);
                }
            }
        }
        return apiLogProducer;
    }
}

